use std::thread;
use std::thread::JoinHandle;
use std::sync::{mpsc, Mutex, Arc};
use std::result::Result::Ok;

enum Message {
    NewJob(Job),
    Terminate
}

trait FnBox {
    fn call_box(self: Box<Self>);
}

impl<F: FnOnce()> FnBox for F {
    fn call_box(self: Box<F>) {
        (*self)()
    }
}

struct Worker {
    id: usize,
    handler: Option<JoinHandle<()>>
}

pub struct PoolThread {
    workers: Vec<Worker>,
    sender: mpsc::Sender<Message>
}

type Job = Box<dyn FnBox + Send + 'static>;

impl Worker {

    fn new(id:usize, receiver: Arc<Mutex<mpsc::Receiver<Message>>>) -> Worker {
        return Worker {id, handler: Some(thread::spawn(move || {
            loop {
                let message = receiver.lock().unwrap().recv().unwrap();
                match message {
                    Message::NewJob(job) => {
                        println!("Worker {} got a job; executing.", id);

                        job.call_box();
                    }
                    Message::Terminate => {
                        println!("Worker {} was told to terminate.", id);
                        break;
                    }
                }
            }
        }))};
    }

}

impl Drop for PoolThread {
    fn drop(&mut self) {
        for _ in &mut self.workers {
            self.sender.send(Message::Terminate).unwrap();
        }
        println!("Shutting down all workers.");
        for worker in &mut self.workers {
            println!("Shutting down worker {}", worker.id);
            if let Some(th) = worker.handler.take() {
                th.join().unwrap();
            }
        }
    }
}

impl PoolThread {

    pub fn new(size: usize) -> PoolThread{
        let mut workers:Vec<Worker> = Vec::with_capacity(size);
        let (sender, receiver) = mpsc::channel();
        let receiver: Arc<Mutex<mpsc::Receiver<Message>>>  = Arc::new(Mutex::new(receiver));
        for i in 0..size {
            let worker= Worker::new(i, Arc::clone(&receiver));
            workers.push(worker)
        }
        return PoolThread{workers, sender};
    }

    pub fn execute<F>(&self, f: F)
        where
            F: FnOnce() + Send + 'static
    {
        let job = Box::new(f);
        self.sender.send(Message::NewJob(job)).unwrap();
    }

}

#[cfg(test)]
mod tests {
    use crate::pool_thread::PoolThread;

    #[test]
    fn test() {
        let pt: PoolThread = PoolThread::new(1);
        pt.execute(|| {
            println!("hello")
        });

    }
}